package com.group.project.hrms.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.group.project.hrms.entity.ContactBasic;
import com.group.project.hrms.entity.ContactBasicDeptInfo;
import com.group.project.hrms.entity.RestTimeSettings;
import com.group.project.hrms.service.ICompanyAttributeService;
import com.group.project.hrms.service.IRestTimeSettingsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;

/**
 * 该类是基本信息工具类，用于处理各类基本信息，例如通讯里基本信息、考勤和薪资计算的基本信息等
 */
@Slf4j
public class BasicInfoUtil {

    @Autowired
    private ICompanyAttributeService iCompanyAttributeService;

    @Autowired
    private IRestTimeSettingsService iRestTimeSettingsService;

    @Autowired
    private DateUtil dateUtil;

    /**
     * 传入部门列表ID集合，返回部门的中文名称
     * @param deptList
     * @param deptInfoList
     * @param sourceFlag
     * @return
     */
    public String getDeptName(String deptList, List<ContactBasicDeptInfo> deptInfoList, int sourceFlag){
        String deptName = "";
        try{
            List<Long> list = JSON.parseArray(deptList, Long.class);
            if(null != list && list.size() == 1){ //大多数情况下，员工只存在于一个部门中
                Long deptId = list.get(0);
                if(deptId == 1){
                    return iCompanyAttributeService.selectAllCompanyAttribute().get(0).getComName();
                }else{
                    for (ContactBasicDeptInfo cbd : deptInfoList
                    ) {
                        if(cbd.getDeptId().equals(deptId) && cbd.getDeptSource() == sourceFlag){
                            deptName = cbd.getDeptName();
                        }
                    }
                }
            }else{
                for (Long deptId : list
                ) {
                    for (ContactBasicDeptInfo cbd : deptInfoList
                    ) {
                        if(cbd.getDeptId().equals(deptId) && cbd.getDeptSource() == sourceFlag){
                            deptName = deptName + "," + cbd.getDeptName();
                        }
                    }
                }
                deptName = deptName.substring(1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return deptName;
    }


    /**
     * 用于筛选离职人员
     * @param orgList
     * @param targetObject
     * @return
     */
    public boolean isInContactBasicLoop(List<ContactBasic> orgList, ContactBasic targetObject){
        for (ContactBasic org : orgList
        ) {
            if(targetObject.getContactId().equals(org.getContactId())){
                return true;
            }
        }
        return false;
    }

    /**
     * 传入一组休息时段集合，先做持久化操作，再返回包含持久化之后的ids和每组休息时间的计算总和（小时，保留一位小数）
     * @param jsonArray
     * @param rids
     * @return
     */
    public Map<String, List<String>> doInsertRestTimeSettings(JSONArray jsonArray, List<String> rids){
        Map<String, List<String>> map = new HashMap<>();
        List<String> totalCountList = new ArrayList<>();
        long total = 0L;
        try{
            if(jsonArray.size() != 0){
                for (Object obj : jsonArray
                ) {
                    JSONArray timezones = JSON.parseObject(JSON.toJSONString(obj)).getJSONArray("timezones");
                    if(null != timezones && timezones.size() != 0){
                        String restTimeId = UUIDUtil.createUUID();
                        rids.add(restTimeId);
                        RestTimeSettings restTimeSettings = new RestTimeSettings();
                        restTimeSettings.setcTime(new Date());
                        restTimeSettings.setRestTimeId(restTimeId);
                        Date endDate = dateUtil.formatDateByString(timezones.getString(1));
                        Date startDate = dateUtil.formatDateByString(timezones.getString(0));
                        total = total + (endDate.getTime() - startDate.getTime());
                        restTimeSettings.setStartTime(startDate);
                        restTimeSettings.setEndTime(endDate);
                        iRestTimeSettingsService.insertRestTimeSettings(restTimeSettings);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        totalCountList.add(String.valueOf(total));
        map.put("ids", rids);
        map.put("total", totalCountList);
        return map;
    }


    /**
     * 传入通讯录集合和部门集合，返回按部门分组后的通讯录集合
     * @param contactBasics
     * @param deptInfos
     * @return
     */
    public Map<String, List<ContactBasic>> doGetAllContactsGroupByDept(List<ContactBasic> contactBasics, List<ContactBasicDeptInfo> deptInfos){
        Map<String, List<ContactBasic>> map = new HashMap<>();
        if(null != contactBasics && null != deptInfos && contactBasics.size() != 0 && deptInfos.size() != 0){
            for (ContactBasicDeptInfo deptInfo : deptInfos
                 ) {
                List<ContactBasic> contactBasicList = new ArrayList<>();
                for (ContactBasic cb : contactBasics
                     ) {
                    JSONArray deptArray = JSONArray.parseArray(cb.getDept());
                    for (Object deptId : deptArray
                         ) {
                        if(deptInfo.getDeptId() == Long.parseLong(deptId.toString())){
                            contactBasicList.add(cb);
                        }
                    }
                }
                map.put(deptInfo.getDeptId().toString(), contactBasicList);
            }
        }
        return map;
    }

    /**
     * 传入部门ID及基础信息集合，返回部门下所有人员基本信息
     * @param contactBasics
     * @param deptInfos
     * @param deptIDs
     * @return
     */
    public List<ContactBasic> doGetAllContactsByDeptIDs(List<ContactBasic> contactBasics, List<ContactBasicDeptInfo> deptInfos, List<Long> deptIDs){
        List<ContactBasic> resultList = new ArrayList<>();
        Map<String, List<ContactBasic>> map = this.doGetAllContactsGroupByDept(contactBasics, deptInfos);
        for (Long id : deptIDs
             ) {
            resultList.addAll(map.get(id.toString()));
        }
        return resultList;
    }

    /**
     * 将部门信息按照部门ID为Key，部门名称为Value 形成Map
     * @param deptInfos
     * @return
     */
    public Map<String, String> doGetDeptMap(List<ContactBasicDeptInfo> deptInfos){
        Map<String, String> deptMap = new HashMap<>();
        if(null != deptInfos && deptInfos.size() != 0){
            for (ContactBasicDeptInfo cbd : deptInfos
                 ) {
                deptMap.put(cbd.getDeptId().toString(), cbd.getDeptName());
            }
        }
        return deptMap;
    }

    /**
     * 该方法将传入的通讯里基本信息集合转换为通讯里Map集合，Map的key为钉钉userid字段
     * @param basicList
     * @return
     */
    public Map<String, ContactBasic> doGetContactMap(List<ContactBasic> basicList){
        Map<String, ContactBasic> resultMap = new HashMap<>();
        if(null != basicList && basicList.size() != 0){
            for (ContactBasic cb : basicList
                 ) {
                resultMap.put(cb.getDingUserid(), cb);
            }
        }
        return resultMap;
    }
}
